package cn.gary.oaserver.config.security;

import cn.gary.oaserver.config.utils.JwtToken;
import cn.gary.oaserver.entity.TAdmin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: 邓必宏
 * @title:
 * @Demo:
 * @DateTime: 2024/3/18
 */
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    JwtToken jwtToken;

    @Autowired
    UserDetailImpl adminService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader ( jwtToken.tokenHeader );
        if ( null!=header  && header.startsWith ( jwtToken.tokenHead )) {
            String parseToken = header.substring ( jwtToken.tokenHead.length ( ) ).trim ( );
            String username = null;
            try {
                username = jwtToken.parseTokenGetUsername ( parseToken );
            } catch (Exception exception) {
                System.out.println ("token失效");
            }
            if (username!=null&& SecurityContextHolder.getContext ().getAuthentication ()==null){

                TAdmin admin= (TAdmin) adminService.loadUserByUsername ( username );

                UsernamePasswordAuthenticationToken token=new UsernamePasswordAuthenticationToken ( admin,null,admin.getAuthorities () );
                SecurityContextHolder.getContext ().setAuthentication ( token );
                token.setDetails ( new WebAuthenticationDetailsSource ().buildDetails ( request ) );
                System.out.println ("上下文所有的权限:"+SecurityContextHolder.getContext ().getAuthentication ().getAuthorities () );

            }
        }
        filterChain.doFilter ( request, response );
    }
}
